//BL0942
#define REC_STATE_WAIT_HEAD     0
#define REC_STATE_REC_DATA      1

static uint8_t uart_frame_buffer[32] = {0};
static uint8_t uart_rec_count = 0;
static uint8_t uart_rec_state = REC_STATE_WAIT_HEAD;
typedef struct struct_data_frame {
    uint8_t HEAD;
    uint32_t I_RMS;
    uint32_t V_RMS;
    uint32_t I_FAST_RMS;
    uint32_t WAIT;
    uint32_t CF_CNT;
    uint32_t FREQ;
    uint32_t STATUS;
    uint8_t CHECKSUM;

} struct_data_frame;
static struct_data_frame data_buffer;

static uint8_t BL0942_ReadAll_Check(uint8_t *data)
{
    uint8_t flg_Comm = 0;
    uint8_t checksum = 0;

    for (int i = 0; i < 22; i++) {
        checksum = checksum + data[i];
    }
    checksum = checksum + 0x58;
    checksum = ~checksum;

    if (data[22] == checksum) {
        flg_Comm = 1;           
    }
    return flg_Comm;
}

static uint32_t uint8_Merge_uint32_LMH(uint8_t L, uint8_t M, uint8_t H)
{
    uint32_t  uMerge = 0;
    uMerge = H;
    uMerge <<= 8;
    uMerge += M;
    uMerge <<= 8;
    uMerge += L;

    return uMerge;
}

static void decode_data(uint8_t *data)
{
    data_buffer.HEAD = data[0];

    data_buffer.I_RMS  = uint8_Merge_uint32_LMH(data[1], data[2], data[3]);
    data_buffer.V_RMS  = uint8_Merge_uint32_LMH(data[4], data[5], data[6]);
    data_buffer.I_FAST_RMS = uint8_Merge_uint32_LMH(data[7], data[8], data[9]);
    data_buffer.WAIT = uint8_Merge_uint32_LMH(data[10], data[11], data[12]);
    data_buffer.CF_CNT = uint8_Merge_uint32_LMH(data[13], data[14], data[15]);
    data_buffer.FREQ = uint8_Merge_uint32_LMH(data[16], data[17], data[18]);
    data_buffer.STATUS = uint8_Merge_uint32_LMH(data[19], data[20], data[21]);

    data_buffer.CHECKSUM = data[22];
}

void uart_rec_byte(uint8_t rec_data)
{
  uart_frame_buffer[uart_rec_count] = rec_data;
  
  if(uart_rec_state == REC_STATE_WAIT_HEAD){
    if(rec_data == 0x55){
      uart_rec_count++;
      uart_rec_state = REC_STATE_REC_DATA;
    }
  }
  else if (uart_rec_state == REC_STATE_REC_DATA) {
    if (uart_rec_count == 22) {
      //checksum is right
      if (BL0942_ReadAll_Check(uart_frame_buffer) == 1) {
        decode_data(uart_frame_buffer);
      }
      uart_rec_count = 0;
      uart_rec_state = REC_STATE_REC_DATA;
    }
    else {
      uart_rec_count++;
    }
  }  
  else{
      uart_rec_count = 0;
      uart_rec_state = REC_STATE_REC_DATA;  
  }
}

uint32_t read_power(void)
{
  uint32_t power;
  power = data_buffer.WAIT;
  power = power*1627;
  power = power/1000000;
  return power;
}

void get_all_data(void)
{
  COM_WriteByte(EMBER_AF_PRINT_CUSTOM2, 0x58);
  COM_WriteByte(EMBER_AF_PRINT_CUSTOM2, 0xaa);
}


//HLW8012
//unit:0.1w        p = f * 0.41378846605;   f = ticks per sec / capture ticks;  ticks per sec = (38400000/256) 